# -*- coding: utf-8 -*-
from future.utils import raise_with_traceback

from common import orm
from common.account.db.account import add_campaign_award_in_transaction
from common.campaign.model.daily_recharge_return import DailyRechargeReturn, DAILY_RECHARGE_AWARD, DAILY_RECHARGE_TYPE 
from common.notification.handler import generate_user_notification, notify_recharge_success
from common.utils.decorator import sql_wrapper
from common.utils.exceptions import ConfigError


@sql_wrapper
def get_daily_recharge(user_id, date_str):
    daily_bet = DailyRechargeReturn.query. \
        filter(DailyRechargeReturn.user_id == user_id). \
        filter(DailyRechargeReturn.date == date_str). \
        first()
    return daily_bet


@sql_wrapper
def set_daily_recharge(user_id, amount, date_str):
    daily_recharge = get_daily_recharge(user_id, date_str)
    if not daily_recharge:
        daily_recharge = DailyRechargeReturn()
        daily_recharge.user_id = user_id
        daily_recharge.date = date_str
        daily_recharge.save()
    daily_recharge.amount = amount
    daily_recharge.save()
    return daily_recharge


def award_daily_recharge(user_id, amount, date_str):
    award_settings = DAILY_RECHARGE_AWARD.get(DAILY_RECHARGE_TYPE.RECHARGE)
    if not award_settings:
        raise ConfigError('DAILY_RECHARGE_TYPE.RECHARGE not found in daily_recharge_award settings')

    award_amount = 0
    for k in award_settings:
        if amount >= k:
            award_amount = max(award_amount, award_settings[k])

    if award_amount <= 0:
        return
    try:
        extend = {
            'title': u'元旦充值大狂欢',
            'award_amount': award_amount
        }
        daily_recharge = DailyRechargeReturn.query.with_for_update(). \
            filter(DailyRechargeReturn.user_id == user_id). \
            filter(DailyRechargeReturn.date == date_str). \
            filter(DailyRechargeReturn.transaction_id.is_(None)). \
            filter(DailyRechargeReturn.is_awarded == 0).first()

        if daily_recharge:
            transaction_id = add_campaign_award_in_transaction(user_id, award_amount, extend)
            daily_recharge.is_awarded = 1
            daily_recharge.amount = amount
            daily_recharge.transaction_id = transaction_id
            daily_recharge.save(auto_commit=False)
            orm.session.commit()
            notify_recharge_success(user_id, u'元旦充值返现', award_amount)
        else:
            orm.session.commit()
    except Exception as e:
        orm.session.rollback()
        orm.session.close()
        raise_with_traceback(e)
